"""YouTube API交互模块"""
import time
import random
import requests
from typing import Dict, Optional, Any
from urllib.parse import urlparse

# API常量
YOUTUBE_API_ENDPOINT = "https://www.googleapis.com/youtube/v3/commentThreads"
MAX_COMMENTS_PER_PAGE = 100
REQUEST_TIMEOUT = 25
MAX_RETRY_ATTEMPTS = 6


def parse_proxy_url(proxy_url: str) -> Optional[Dict[str, str]]:
    """解析代理URL并生成代理配置"""
    try:
        parsed = urlparse(proxy_url)
        
        if parsed.scheme not in ('http', 'https'):
            print("警告：代理地址必须以http://或https://开头")
            return None
            
        if not parsed.hostname or not parsed.port:
            print("警告：代理地址格式无效，必须包含主机和端口（例如：http://host:port）")
            return None
            
        proxy_config = {
            'http': proxy_url,
            'https': proxy_url
        }
        
        if parsed.username and parsed.password:
            log_url = f"{parsed.scheme}://{parsed.username}:***@{parsed.hostname}:{parsed.port}"
        else:
            log_url = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}"
            
        print(f"INFO | 使用代理: {log_url}")
        return proxy_config
        
    except Exception as e:
        print(f"警告：解析代理地址失败: {str(e)}，将不使用代理")
        return None


def exponential_backoff(retry_count: int) -> None:
    """指数退避策略"""
    base_delay = 1.5
    jitter = random.uniform(0.3, 0.8)
    delay = min(60, (base_delay ** retry_count) + jitter)
    print(f"DEBUG | 第 {retry_count+1} 次重试，等待 {delay:.2f} 秒")
    time.sleep(delay)


def fetch_comment_page(page_token: Optional[str], proxy: Optional[Dict[str, str]], 
                      video_id: str, api_key: str) -> Dict[str, Any]:
    """获取单页评论数据"""
    request_params = {
        "part": "snippet,replies",
        "videoId": video_id,
        "maxResults": MAX_COMMENTS_PER_PAGE,
        "textFormat": "plainText",
        "key": api_key
    }
    
    if page_token:
        request_params["pageToken"] = page_token

    request_headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
    }

    for retry in range(MAX_RETRY_ATTEMPTS):
        try:
            response = requests.get(
                url=YOUTUBE_API_ENDPOINT,
                headers=request_headers,
                params=request_params,
                proxies=proxy,
                timeout=REQUEST_TIMEOUT,
                verify=True
            )
            
            if response.status_code == 200:
                return response.json()
            elif response.status_code in (403, 429, 500, 502, 503, 504):
                error_msg = response.text[:200]
                print(f"WARNING | 请求失败（状态码: {response.status_code}）: {error_msg}")
                exponential_backoff(retry)
            else:
                response.raise_for_status()
                
        except requests.RequestException as e:
            print(f"WARNING | 网络请求异常: {str(e)}")
            exponential_backoff(retry)
            
    raise RuntimeError(f"超过最大重试次数（{MAX_RETRY_ATTEMPTS} 次）")
    